package com.xlh.controller.course;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.xlh.common.Result;
import com.xlh.common.ResultEnum;
import com.xlh.constant.UserConstant;
import com.xlh.dto.course.TemplateDTO;
import com.xlh.dto.course.TemplateInfoDTO;
import com.xlh.enums.ResourcesTypeEnum;
import com.xlh.enums.course.TemplateTypeEnum;
import com.xlh.param.ValidList;
import com.xlh.param.course.FileParam;
import com.xlh.param.course.TemplateInfoParam;
import com.xlh.param.course.TemplateParam;
import com.xlh.security.UserInfoHolder;
import com.xlh.service.course.ChapterService;
import com.xlh.service.course.TemplateService;
import com.xlh.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 模版
 * <p>
 * Created by lx on 2019/1/25.
 */
@Api(tags = "TemplateController", description = "模版")
@RestController
@RequestMapping("/template")
public class TemplateController {

    @Autowired
    private TemplateService templateService;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private UserInfoHolder userInfoHolder;

    @ApiOperation("查询模版数据")
    @GetMapping
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result<Map<String, TemplateDTO>> queryTemplate(
            @RequestParam @ApiParam(value = "模板类型 1：实验课报告模板 2：实验考试报告模板", required = true) Integer type) {
        Long userId = userInfoHolder.getUserId();
        return Result.success(templateService.queryTemplateInfo(userId, TemplateTypeEnum.getByCode(type)));
    }

    @ApiOperation("查询模板数据")
    @GetMapping("/evaluation")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result<List<TemplateInfoDTO>> queryTemplateInfo(@RequestParam Integer type) {
        Long userId = userInfoHolder.getUserId();
        return Result.success(templateService.queryTemplates(userId, TemplateTypeEnum.getByCode(type)));
    }

    @ApiOperation("保存模板数据")
    @PostMapping("/evaluation")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result<List<TemplateInfoDTO>> saveTemplate(
            @RequestParam Integer type, @RequestBody @Valid ValidList<TemplateInfoParam> params) {
        Long userId = userInfoHolder.getUserId();
        templateService.updateTemplateInfo(userId, TemplateTypeEnum.getByCode(type), params);
        return Result.success();
    }

    @ApiOperation("上传模版")
    @PostMapping()
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result createOrUpdateTemplate(
            @RequestParam @ApiParam(value = "模板类型 1：实验课报告模板 2：实验考试报告模板", required = true) Integer type,
            @RequestParam @ApiParam(value = "资源类型", required = true) Integer resourceType,
            @RequestParam(required = false) @ApiParam(value = "上传的文件") MultipartFile file) {
        templateService.createOrUpdateTemplate(file, null,
                TemplateTypeEnum.getByCode(type), ResourcesTypeEnum.getByCode(resourceType));
        return Result.success();
    }

    @ApiOperation("添加/编辑模版保存")
    @PostMapping("/online")
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result createOrUpdateOnlineTemplate(
            @RequestParam @ApiParam(value = "模板类型 1：实验课报告模板 2：实验考试报告模板", required = true) Integer type,
            @RequestParam @ApiParam(value = "资源类型", required = true) Integer resourceType,
            @RequestBody TemplateParam param) {
        templateService.createOrUpdateTemplate(null, param.getEditorContent(),
                TemplateTypeEnum.getByCode(type), ResourcesTypeEnum.getByCode(resourceType));
        return Result.success();
    }

    @ApiOperation("删除模版")
    @DeleteMapping()
    @PreAuthorize("@permissionValidator.isAdmin()")
    public Result deleteWordTemplate(
            @RequestParam @ApiParam(value = "模板类型 1：实验课报告模板 2：实验考试报告模板", required = true) Integer type) {
        templateService.deleteTemplateResources(TemplateTypeEnum.getByCode(type));
        return Result.success();
    }

    @ApiOperation("重置为通用模板")
    @PutMapping("/reset")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result resetCommonTemplate(
            @RequestParam @ApiParam(value = "模板类型 1：实验课报告模板 2：实验考试报告模板", required = true) Integer type,
            @RequestParam @ApiParam(value = "资源类型", required = true) Integer resourceType) {
        templateService.resetCommonTemplate(TemplateTypeEnum.getByCode(type),
                ResourcesTypeEnum.getByCode(resourceType));
        return Result.success();
    }

    @ApiOperation("是否允许下载资源文件")
    @PostMapping("/download/permission")
    public Result<String> fileDownloadPermission(
            @RequestParam @ApiParam(value = "模板类型 1：实验课报告模板 2：实验考试报告模板", required = true) Integer type,
            @RequestBody @Valid FileParam param) {
        templateService.checkResource(type, param.getFileName());
        String uuid = RandomUtil.simpleUUID();
        UserConstant.DOWNLOAD_FILE_MAP.put(userInfoHolder.getUserId() + uuid, param);
        return Result.success(uuid);
    }

    @ApiOperation("下载资源文件")
    @GetMapping("/download")
    public Result<String> fileDownload(
            HttpServletResponse response,
            @RequestParam @ApiParam(value = "模板类型 1：实验课报告模板 2：实验考试报告模板", required = true) Integer type,
            @RequestParam @ApiParam(value = "token", required = true) String token) {

        FileParam param = chapterService.getTokenValueAndRemove(token);
        String filePath = templateService.checkResource(type, param.getFileName());

        // 下载资源
        try {
            String fileName = StringUtils.join(
                    TemplateTypeEnum.getByCode(type).getMessage(),
                    ".",
                    StrUtil.subAfter(param.getFileName(), ".", true)
            );
            FileUtil.downloadFile(response, filePath, fileName);
        } catch (Exception e) {
            return Result.error(ResultEnum.SERVER_ERROR);
        }

        return Result.success();
    }


}
